import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginGuard } from 'src/app/guard/login.guard';
import { AuthService, SysUser } from 'src/app/service/business/auth.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MessageService } from 'primeng/api';
import * as models from 'src/app/global/model';
import { SysuserService } from 'src/app/service/business/sysuser.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers:[ MessageService ]
})
export class LoginComponent implements OnInit {

  loginForm:FormGroup;

  constructor(
    private router:Router,
    private authService:AuthService,
    private fb:FormBuilder,
    private msgService:MessageService,
    private sysUserService:SysuserService
  ) { 
    this.initLoginForm();
    this.initRxSubject();
  }

  ngOnInit() {
  }

  // 初始化响应式对象
  initRxSubject(){
    // 订阅编号变动
    this.loginForm.get('userId').valueChanges.pipe(debounceTime(1000)).subscribe(
      ( res ) => {

        this.sysUserService.selectByUserId(res).subscribe(
          ( res:models.JsonResult ) => {
            if( res.code !==1 ){// 根据用户编号没有获取对应的用户信息
              this.loginForm.patchValue({'username':''});
              this.msg(res.msg);
            }else{// 成功获取到账号信息
              let user:SysUser = res.data;
              this.loginForm.patchValue({'userName':user.username});
            }
          }
        )

      }
    )
    

  }

  // 初始化登录表单
  initLoginForm(){
    this.loginForm = this.fb.group({
      userId:[null,Validators.required],
      userName:[{value:null,disabled:true},Validators.required],
      password:[null,Validators.required]
    });
  }

  submitForm(){
    let userId = this.loginForm.value["userId"];
    let userName = this.loginForm.value["userName"];
    let password = this.loginForm.value["password"];

    let tip = userId + "," + userName + "," + password;

    this.msg(tip);

    let loginUser:SysUser = new SysUser();
    loginUser.username = userId;
    loginUser.password = password;

    this.authService.login(loginUser).subscribe(
      ( res:models.JsonResult )=> {
        if( res.code === 1 ){
          this.authService.isLoggedIn = true;
          this.msg('登录成功！');
          this.router.navigate(['/layout']);
        }else{
          this.msg(res.msg);
        }
        
      }
      ,error => console.log('登录时出现异常！')
    )
  }


  msg(content:string) {
    this.msgService.add({key: 'custom', severity:'info', summary: '通知', detail:content});
  }


}
